import { utilJs, deviceUtil } from '@/utils/common.js';

export const SCENE_ENUM = {
  SCENE_PAGE_VIEW: 10, // 访问
  SCENE_PAGE_SHARE: 11, // 主动分享
  SCENE_PAGE_STAYTIME: 13, // 页面停留时长（详情页）
  SCENE_PAGE_CLICK : 14, // 页面点击/切换 目前只有vip切换规格在使用
  SCENE_PAGE_DEEP: 15, // 页面访问深度
  SCENE_PAGE_STAYTIME_ALL : 16, // 页面停留时长（所有页面）
  SCENE_USER_LEARNING: 40, // 用户学习访问行为（有权限）
};

export const PAGE_ENUM = {
  PAGE_HOME: 1, // 首页
  PAGE_DETAIL: 3, // 详情页
  PAGE_MICRO: 10, // 微页面
};

export const PROD_TYPE_ENUM = {
  VIDEO: 110, // 视频
  VOICE: 111, // 音频
  IMAGE_TEXT: 112, // 图文
  COLUMN: 9, // 专栏
  DISTRIBUTION_COLUMN: 103,
  CAMP: 78, // 训练营
  PACKAGE: 61, // 知识套餐
  EBOOKS: 142, // 电子书
  BOOKING: 86, //预约师资
  DATUN: 8, // 资料
  LIVE: 51, // 公开课
  PERSONAL_LIVE: 180, // 直播间
  PRIVATE_CLASS: 115, // 小班课
  EDU: 116, // 小班课
  CLOCK_IN: 41, // 打卡
  CIRCLE: 181, // 圈子
  TEST_PAPER: 125, // 考试
  ITEM_RANK: 129, // 练习
  EXAM: 11, // 测评专题
  MUTUA_TEST: 75, // 互动测评
  AI_TEST: 77, // AI测评
  ACTIVITY: 7, // 活动
  RESERVATION: 53, // 约课
  SOCIAL: 10, // 社群
  MALL: 12, // 商城
  VIP: 1, // VIP
  SVIP: 23 // SVIP
};
const PAGE_PROD_INFO = {
  prodType:'',
  prodId:'',
}
const PAGE_STAY_TIME = {
  enterTimeTmp: 0,
  leaveTimeTmp: 0
};
const APP_STAY_DATA = {
  timeControl: null, //定时上报时长定时器
  deep: 0, // 页面访问深度
  enterTimeTmp: 0,
  leaveTimeTmp: 0
};
const MICRO_PROD_TYPE = 196; //微页面产品类型固定使用196

export function getDetailPageMapByRouter(curQuery) {
  const DETAIL_PAGE_PATH_MAP = {
    '/homePage/microPage/microPage': { pId: curQuery.mId, pType: MICRO_PROD_TYPE },
    '/homePage/course/video': { pId: curQuery.distributionId ? curQuery.extId : curQuery.courseId, pType: curQuery.distributionId ? PROD_TYPE_ENUM.DISTRIBUTION_COLUMN : PROD_TYPE_ENUM.VIDEO }, //内容市场带了distribution标识
    '/homePage/course/voice': { pId: curQuery.distributionId ? curQuery.extId : curQuery.courseId, pType: curQuery.distributionId ? PROD_TYPE_ENUM.DISTRIBUTION_COLUMN : PROD_TYPE_ENUM.VOICE }, //内容市场带了distribution标识
    '/homePage/course/imgText': { pId: curQuery.distributionId ? curQuery.extId : curQuery.courseId, pType: curQuery.distributionId ? PROD_TYPE_ENUM.DISTRIBUTION_COLUMN : PROD_TYPE_ENUM.IMAGE_TEXT }, //内容市场带了distribution标识
    '/homePage/column/columnDetail': { pId: curQuery.extId, pType: curQuery.distribution ? PROD_TYPE_ENUM.DISTRIBUTION_COLUMN : PROD_TYPE_ENUM.COLUMN }, //内容市场带了distribution标识
    '/homePage/booking/bookingTime': { pId: curQuery.atId, pType: PROD_TYPE_ENUM.BOOKING },
    '/homePage/booking/bookingDetail': { pId: curQuery.atId, pType: PROD_TYPE_ENUM.BOOKING },
    '/homePage/camp/campDetail': { pId: curQuery.campId, pType: PROD_TYPE_ENUM.CAMP },
    '/homePage/package/packageDetail': { pId: curQuery.combosId, pType: PROD_TYPE_ENUM.PACKAGE },
    '/homePage/ebooks/ebooksDetail': { pId: curQuery.id, pType: PROD_TYPE_ENUM.EBOOKS },
    '/homePage/ebooks/ebooks': { pId: curQuery.ebId, pType: PROD_TYPE_ENUM.EBOOKS },
    '/homePage/datum/datumDetail': { pId: curQuery.datumId, pType: PROD_TYPE_ENUM.DATUN },
    '/homePage/live/liveDetail': { pId: curQuery.liveId, pType: PROD_TYPE_ENUM.LIVE },
    '/homePage/live/liveRoom': { pId: curQuery.liveId, pType: PROD_TYPE_ENUM.LIVE },
    '/homePage/live/liveVerticalRoom': { pId: curQuery.liveId, pType: PROD_TYPE_ENUM.LIVE },
    '/homePage/live/livePersonalDetail': { pId: curQuery.liveId, pType: PROD_TYPE_ENUM.PERSONAL_LIVE },
    '/homePage/live/liveVHRoom': { pId: curQuery.liveId, pType: PROD_TYPE_ENUM.PERSONAL_LIVE },
    '/homePage/privateClass/classDetail': { pId: curQuery.classId, pType: PROD_TYPE_ENUM.PRIVATE_CLASS },
    '/homePage/clockIn/clockInDetail': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/stuHomeWork': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/simpleQue': { pId: curQuery.clockId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/shortAnswerResult': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/rankList': { pId: curQuery.clockId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/studyHistory': { pId: curQuery.clockId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/stuShortAnswerResult': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/stuHomeWorkDiary': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/voiceQue': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/voiceResult': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/homeWorkResult': { pId: curQuery.clockInId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/answerAnalyze': { pId: curQuery.clockId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/clockIn/choiceQue': { pId: curQuery.clockId, pType: PROD_TYPE_ENUM.CLOCK_IN },
    '/homePage/circle/circleFeed': { pId: curQuery.id, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/circle/circleMaster': { pId: curQuery.id, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/circle/circleRelease': { pId: curQuery.id, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/circle/circleIndex': { pId: curQuery.circleId, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/circle/integralRankIndex': { pId: curQuery.id, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/circle/circleData': { pId: curQuery.circleId, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/circle/circleFriends': { pId: curQuery.circleId, pType: PROD_TYPE_ENUM.CIRCLE },
    '/homePage/testPaper/testDetail': { pId: curQuery.testId, pType: PROD_TYPE_ENUM.TEST_PAPER },
    '/homePage/examination/examinationAnswer': { pId: curQuery.paperMainId, pType: curQuery.topicId ? PROD_TYPE_ENUM.EXAM : PROD_TYPE_ENUM.TEST_PAPER }, //考试和测评用的同个页面，测评连接上带了topicId
    '/homePage/examination/examinationResult': { pId: curQuery.paperMainId, pType: curQuery.topicId ? PROD_TYPE_ENUM.EXAM : PROD_TYPE_ENUM.TEST_PAPER }, //考试和测评用的同个页面，测评连接上带了topicId
    '/homePage/examination/examinationAnswerAnalyze': { pId: curQuery.paperMainId, pType: curQuery.topicId ? PROD_TYPE_ENUM.EXAM : PROD_TYPE_ENUM.TEST_PAPER }, //考试和测评用的同个页面，测评连接上带了topicId
    '/homePage/examination/examinationRank': { pId: curQuery.paperMainId, pType: curQuery.topicId ? PROD_TYPE_ENUM.EXAM : PROD_TYPE_ENUM.TEST_PAPER }, //考试和测评用的同个页面，测评连接上带了topicId
    '/homePage/itemBank/questionSaleDetail': { pId: curQuery.libraryId, pType: PROD_TYPE_ENUM.ITEM_RANK },
    '/homePage/itemBank/practiceModes': { pId: curQuery.practiceId, pType: PROD_TYPE_ENUM.ITEM_RANK },
    '/homePage/itemBank/questionCollect': { pId: curQuery.libraryId, pType: PROD_TYPE_ENUM.ITEM_RANK },
    '/homePage/itemBank/practiceMode': { pId: curQuery.practiceId, pType: PROD_TYPE_ENUM.ITEM_RANK },
    '/homePage/itemBank/questionAnswer': { pId: curQuery.libraryId, pType: PROD_TYPE_ENUM.ITEM_RANK },
    '/homePage/itemBank/questionResult': { pId: curQuery.libraryId, pType: PROD_TYPE_ENUM.ITEM_RANK },
    '/homePage/examination/examinationDetail': { pId: curQuery.ExaminationNo, pType: PROD_TYPE_ENUM.EXAM },
    '/homePage/mutuaTest/mutuaTestDetail': { pId: curQuery.mutuaTestId, pType: PROD_TYPE_ENUM.MUTUA_TEST },
    '/homePage/mutuaTest/mutuaAnswer': { pId: curQuery.paperMainId, pType: PROD_TYPE_ENUM.MUTUA_TEST },
    '/homePage/mutuaTest/mutuaResult': { pId: curQuery.paperMainId, pType: PROD_TYPE_ENUM.MUTUA_TEST },
    '/homePage/voiceTest/voiceTestDetail': { pId: curQuery.paperMainId, pType: PROD_TYPE_ENUM.AI_TEST },
    '/homePage/voiceTest/voiceTestAnswer': { pId: curQuery.paperMainId, pType: PROD_TYPE_ENUM.AI_TEST },
    '/homePage/voiceTest/voiceTestResult': { pId: curQuery.paperMainId, pType: PROD_TYPE_ENUM.AI_TEST },
    '/homePage/voiceTest/voiceTestRank': { pId: curQuery.paperMainId, pType: PROD_TYPE_ENUM.AI_TEST },
    '/activity/activityDetail': { pId: curQuery.ActivityNo, pType: curQuery.from == 'reservation' || curQuery.from == 'sectionInfo' ? PROD_TYPE_ENUM.RESERVATION : PROD_TYPE_ENUM.ACTIVITY }, // 活动和约课用的同一个页面地址
    '/homePage/socialGroup/socialGroupInfo': { pId: curQuery.SocialRoomId, pType: PROD_TYPE_ENUM.SOCIAL },
    '/mall/shopDetail/shopDetail': { pId: curQuery.ShopNo || curQuery.shopNo, pType: PROD_TYPE_ENUM.MALL },
    '/edu/eduDetail': { pId: curQuery.id, pType: PROD_TYPE_ENUM.EDU },
    '/edu/eduDetail/': { pId: curQuery.id, pType: PROD_TYPE_ENUM.EDU },
    // '/member/vip/vipUp': { pId: curQuery.cmpId || 0, pType: curQuery.type == 23 ? PROD_TYPE_ENUM.SVIP : PROD_TYPE_ENUM.VIP }, // SVIP类型和VIP同个页面地址
    // '/member/vip/vipDetail': { pId: curQuery.cmpId || 0, pType: curQuery.type == 23 ? PROD_TYPE_ENUM.SVIP : PROD_TYPE_ENUM.VIP } // SVIP类型和VIP同个页面地址
  };
  return DETAIL_PAGE_PATH_MAP;
}
/**
 * 是否访问店铺
 * @returns {Boolean}
 */
export function checkIsViewShop(curPath, fromPath) {
  const LIST_PATH_ARR = [
    '/message/messageIndex', // 消息列表
    '/homePage/reservation/reservationList', // 约课
    '/mall/classification/classificationAll', // 商城
    '/homePage/distribution/distributionList', // 分销商城
    '/edu/eduList', // 面授课
    '/homePage/course/courseList', // 课程列表
    '/homePage/column/columnList', // 专栏列表
    '/homePage/camp/campList', // 训练营列表
    '/homePage/package/packageList', // 知识套餐列表
    '/homePage/datum/datumList', // 资料列表
    '/homePage/ebooks/ebooksList', // 电子书列表
    '/homePage/clockIn/clockInList', // 打卡列表
    '/homePage/circle/circleList', // 圈子列表
    '/homePage/testPaper/testList', // 考试列表
    '/homePage/itemBank/questionList', // 练习列表
    '/homePage/examination/examinationList', // 测评专题列表
    '/homePage/mutuaTest/mutuaTestList', // 互动测评列表
    '/homePage/voiceTest/voiceTestList', // ai测评列表
    '/activity/activityIndex', // 活动/约课列表
    '/homePage/socialGroup/socialGroupList', // 社群列表
    '/homePage/valueVoucher/list', // 优惠券列表
    '/homePage/qa/answerLord', // 问答列表
    '/homePage/qa/AnswerLord', // 问答列表
    '/homePage/word/wordList', // 词典列表
    '/homePage/live/liveList', // 公开课列表
    '/homePage/live/livePersonalList', // 直播间列表
    '/homePage/privateClass/classList', // 小班课列表
    '/homePage/booking/bookingList', // 预约列表
    '/homePage/collage/collageList', // 拼团列表
    '/homePage/bargain/bargainList', // 砍价列表
    '/homePage/flashSales/flashSalesList', // 限时购列表
    '/homePage/task/taskList', // 友情灌溉列表
    '/member/myExchange/valuableCouponList', // 有价券列表
    '/homePage/collocationBuy/collocationBuyList', // 搭配购列表
    '/member/memberIndex', // 个人中心
    '/member/recommend/recommendIndex' // 推荐有礼分享页
  ];
  //不是微页面的首页
  if (curPath == '/' && !localStorage.getItem('mId')) {
    return true;
  }
  //套壳小程序首页
  if (curPath == '/' && Vue.prototype.$isWxApp()) {
    return true;
  }
  if (LIST_PATH_ARR.includes(curPath)) {
    return true;
  }
  return false;
}

/**
 * 检查是不是微页面首页
 */
export function getMicroPageIndexId(curPath) {
  //小程序套壳不上报微页面数据
  if (Vue.prototype.$isWxApp()) {
    return null;
  }
  //微页面设置成首页
  if (curPath == '/' && localStorage.getItem('mId')) {
    return localStorage.getItem('mId');
  }
  return null;
}

/**
 * 检查是不是vip页面
 * @param {string} curPath 页面路由地址
 * @returns 是否是vip页面
 */
export function checkIsVipPage(curPath) {
  if (curPath == '/member/vip/vipUp') {
    return true;
  }
  if (curPath == '/member/vip/vipDetail') {
    return true;
  }
  return false;
}

/**
 * 上报用户行为轨迹
 * @param {number} se 场景值
 * @param {number} pg 页面
 * @param {object} evt 具体事件行为
 * @param {string} evt.pId - 产品id
 * @param {number} evt.pType - 产品类型
 * @param {number} evt.st - 进入页面时间戳
 * @param {number} evt.et - 离开页面时间戳
 * @param {number} evt.dur - 页面停留时长 单位毫秒
 */
export function reportTraceLog(se, pg, evt = {}) {
  const sid = sessionStorage.getItem('shareFromUserId') || '';
  const data = {
    se,
    pg,
    sid,
    evt
  };
  utilJs.postMethod(global.apiurl + 'analyse/userTraceLog', data);
}
/**
 * 关闭页面的时候，上报用户行为轨迹
 * @param {number} se 场景值
 * @param {number} pg 页面
 * @param {object} evt 具体事件行为
 * @param {string} evt.pId - 产品id
 * @param {number} evt.pType - 产品类型
 * @param {number} evt.st - 进入页面时间戳
 * @param {number} evt.et - 离开页面时间戳
 * @param {number} evt.dur - 页面停留时长 单位毫秒
 */
export function reportTraceLogByBeacon(se, pg, evt = {}) {
  const postData = new FormData();
  const companyId = localStorage.getItem('companyId');
  const userId = localStorage.getItem('userId');
  const sid = sessionStorage.getItem('shareFromUserId') || '';
  postData.append('c', companyId);
  postData.append('u', userId);
  postData.append('se', se);
  postData.append('pg', pg);
  postData.append('sid', sid);
  postData.append('evt', JSON.stringify(evt));
  postData.append('Authorization', `Bearer ${localStorage.getItem('token')}`);
  postData.append('X-STORE-ID', utilJs.getStoreId());
  postData.append('X-Trace-Ch', utilJs.getFromApplicationNum());
  postData.append('postMethods', 'sendBeacon');
  if (navigator.sendBeacon) {
    navigator.sendBeacon(`${global.apiurl}analysis/userTraceLogByClose?event=destroyed`, postData);
  }
}

/**
 * 根据当前页面路由的变化上报页面的访问记录
 * @param {object} to 页面路由to
 * @param {object} from 页面路由from
 */
export function reportPageViewByRouter(to, from) {
  const curPath = to.path;
  const curQuery = to.query || {};
  const fromPath = from && from.path;
  const DETAIL_PAGE_PATH_MAP = getDetailPageMapByRouter(curQuery);
  // 通过首页链接、二维码，访问首页,不记录通过其他路径到首页的行为
  if (checkIsViewShop(curPath, fromPath)) {
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_VIEW, PAGE_ENUM.PAGE_HOME);
  }
  // 只有访问产品详情页才数据上报
  if (DETAIL_PAGE_PATH_MAP[curPath]) {
    //微页面特殊处理pg=10
    const pg = DETAIL_PAGE_PATH_MAP[curPath].pType == MICRO_PROD_TYPE ? PAGE_ENUM.PAGE_MICRO : PAGE_ENUM.PAGE_DETAIL;
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_VIEW, pg, DETAIL_PAGE_PATH_MAP[curPath]);
  }
  //微页面首页数据上报
  const microId = getMicroPageIndexId(curPath);
  if (microId) {
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_VIEW, PAGE_ENUM.PAGE_MICRO, {pId:microId, pType:MICRO_PROD_TYPE});
  }
  ++APP_STAY_DATA.deep

  console.log('当前访问deep:', APP_STAY_DATA.deep)
}
/**
 * 详情页面点击按钮上报浏览，目前主要是vip切换规格的时候需要上报选中的vip产品id和类型
 * @param {Object} prodInfo
 * @param {string} prodInfo.prodId
 * @param {number} prodInfo.prodType
 */
export function reportPageViewByBtn(prodInfo = {}) {
  const {prodId, prodType} = prodInfo;
  if (prodId == -1) {
    return;
  }
  const evt = {
    pId: prodId,
    pType: prodType
  };
  reportTraceLog(SCENE_ENUM.SCENE_PAGE_VIEW, PAGE_ENUM.PAGE_DETAIL, evt);
  //切换到不同规格的时候上报上个规格的浏览时长
  if (PAGE_PROD_INFO.prodId && PAGE_PROD_INFO.prodId != prodId) {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      pId:PAGE_PROD_INFO.prodId,
      pType: PAGE_PROD_INFO.prodType,
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    };
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_STAYTIME, PAGE_ENUM.PAGE_DETAIL, evt);
    PAGE_STAY_TIME.enterTimeTmp = Date.now();
  }
  PAGE_PROD_INFO.prodId = prodId;
  PAGE_PROD_INFO.prodType = prodType;
}

/**
 * 上报学习记录
 */
export function reportProdStudy(pId, pType) {
  const evt = {
    pId,
    pType,
  };
  reportTraceLog(SCENE_ENUM.SCENE_USER_LEARNING, PAGE_ENUM.PAGE_DETAIL, evt);
}

/**
 * 页面分享成功上报
 * @param {string} shareUrl 当前分享的链接
 */
export function reportPageShareSuccess(shareUrl) {
  if (!shareUrl) {
    return;
  }
  const curPath = utilJs.getUrlRoutePath(shareUrl);
  const curQuery = utilJs.parseUrlQueryParams(shareUrl);
  const DETAIL_PAGE_PATH_MAP = getDetailPageMapByRouter(curQuery);
  // 产品详情页调用微信分享结果上报,包含邀请卡的分享
  if (DETAIL_PAGE_PATH_MAP[curPath]) {
    //微页面特殊处理pg=10
    const pg = DETAIL_PAGE_PATH_MAP[curPath].pType == MICRO_PROD_TYPE ? PAGE_ENUM.PAGE_MICRO : PAGE_ENUM.PAGE_DETAIL;
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_SHARE, pg, DETAIL_PAGE_PATH_MAP[curPath]);
  }
  //微页面首页数据上报
  const microId = getMicroPageIndexId(curPath);
  if (microId) {
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_SHARE, PAGE_ENUM.PAGE_MICRO, {pId:microId, pType:MICRO_PROD_TYPE});
  }
  //vip页面分享结果上报
  if (checkIsVipPage(curPath) && PAGE_PROD_INFO.prodId) {
    const evt = {
      pId:curQuery.cmpId || PAGE_PROD_INFO.prodId,
      pType: curQuery.type == 1 ? PROD_TYPE_ENUM.VIP : curQuery.type == 23 ? PROD_TYPE_ENUM.SVIP : PAGE_PROD_INFO.prodType
    }
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_SHARE, PAGE_ENUM.PAGE_DETAIL, evt);
  }
}

/**
 * 产品详情页面停留时长上报
 * @param {object} to 页面路由to
 * @param {object} from 页面路由from
 */
export function reportPageViewTime(to, from) {
  const curPath = to.path;
  const curQuery = from.query || {};
  const fromPath = from && from.path;
  const DETAIL_PAGE_PATH_MAP = getDetailPageMapByRouter(curQuery);
  // 离开了要统计时长的详情页面了
  if (DETAIL_PAGE_PATH_MAP[fromPath]) {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      ...DETAIL_PAGE_PATH_MAP[fromPath],
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    };
    //微页面特殊处理pg=10
    const pg = DETAIL_PAGE_PATH_MAP[fromPath].pType == MICRO_PROD_TYPE ? PAGE_ENUM.PAGE_MICRO : PAGE_ENUM.PAGE_DETAIL;
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_STAYTIME, pg, evt);
  }
  //离开了要统计时长的vip页面
  if (checkIsVipPage(fromPath) && PAGE_PROD_INFO.prodId) {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      pId:PAGE_PROD_INFO.prodId,
      pType: PAGE_PROD_INFO.prodType,
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    };
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_STAYTIME, PAGE_ENUM.PAGE_DETAIL, evt);
  }
  // 离开了要统计时长的微页面首页了，
  const microId = getMicroPageIndexId(fromPath);
  //防止首次进入curpath也是首页，fromPath也是首页就直接上报停留时长
  if (microId && curPath != '/') {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      pId:microId,
      pType:MICRO_PROD_TYPE,
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    };
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_STAYTIME, PAGE_ENUM.PAGE_MICRO, evt);
  }

  PAGE_STAY_TIME.enterTimeTmp = Date.now();
  PAGE_PROD_INFO.prodType = '';
  PAGE_PROD_INFO.prodId = '';
}

/**
 * 通过切换后台和关闭页面上报用户在产品详情页停留时长行为
 */
export function reportPageViewTimeOnVisbile() {
  const curUrl = window.location.href;
  const curPath = utilJs.getUrlRoutePath(curUrl);
  const curQuery = utilJs.parseUrlQueryParams(curUrl);
  const DETAIL_PAGE_PATH_MAP = getDetailPageMapByRouter(curQuery);
  //上报访问详情页的时长
  if (DETAIL_PAGE_PATH_MAP[curPath]) {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      ...DETAIL_PAGE_PATH_MAP[curPath],
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    };
    //微页面特殊处理pg=10
    const pg = DETAIL_PAGE_PATH_MAP[curPath].pType == MICRO_PROD_TYPE ? PAGE_ENUM.PAGE_MICRO : PAGE_ENUM.PAGE_DETAIL;
    reportTraceLogByBeacon(SCENE_ENUM.SCENE_PAGE_STAYTIME, pg, evt);
  }
  //上报访问vip页面的时长
  if (checkIsVipPage(curPath) && PAGE_PROD_INFO.prodId) {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      pId:PAGE_PROD_INFO.prodId,
      pType: PAGE_PROD_INFO.prodType,
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    }
    reportTraceLogByBeacon(SCENE_ENUM.SCENE_PAGE_STAYTIME, PAGE_ENUM.PAGE_DETAIL, evt);
  }
   //上报访问微页面首页的时长
   const microId = getMicroPageIndexId(curPath);
   if (microId) {
    PAGE_STAY_TIME.leaveTimeTmp = Date.now();
    PAGE_STAY_TIME.enterTimeTmp = PAGE_STAY_TIME.enterTimeTmp || Date.now();
    const viewTime = PAGE_STAY_TIME.leaveTimeTmp - PAGE_STAY_TIME.enterTimeTmp;
    const evt = {
      pId:microId,
      pType:MICRO_PROD_TYPE,
      st: Math.floor(PAGE_STAY_TIME.enterTimeTmp / 1000),
      et: Math.floor(PAGE_STAY_TIME.leaveTimeTmp / 1000),
      dur: Math.floor(viewTime / 1000)
    };
    reportTraceLogByBeacon(SCENE_ENUM.SCENE_PAGE_STAYTIME, PAGE_ENUM.PAGE_MICRO, evt);
  }
  // 上报用户在系统停留的总时长
  APP_STAY_DATA.leaveTimeTmp = Date.now();
  APP_STAY_DATA.enterTimeTmp = APP_STAY_DATA.enterTimeTmp || Date.now();
  const appStayTime = APP_STAY_DATA.leaveTimeTmp - APP_STAY_DATA.enterTimeTmp;
  const appEvt = {
    'dp': APP_STAY_DATA.deep,
    'st': Math.floor(APP_STAY_DATA.enterTimeTmp / 1000),
    'et': Math.floor(APP_STAY_DATA.leaveTimeTmp / 1000),
    'dur': Math.floor(appStayTime / 1000)
  }
  //防止上报两次，第二次的entertime还是比较早
  APP_STAY_DATA.enterTimeTmp = Date.now();
  reportTraceLogByBeacon(SCENE_ENUM.SCENE_PAGE_DEEP, PAGE_ENUM.PAGE_HOME, appEvt);
  reportTraceLogByBeacon(SCENE_ENUM.SCENE_PAGE_STAYTIME_ALL, PAGE_ENUM.PAGE_HOME, appEvt);
  APP_STAY_DATA.deep = 1;
}

/**
 * 应用程序切后台事件监听，在用户切后台的时候，上报停留时长，
 * 切回前台的时候，重置进入页面的时间，防止把切后台事件也算进去停留时间
 */
export function initAppVisibilityChangeEvent() {
  //ios设备直接右上角关闭页面无法触发visibilitychange，尝试使用pagehide上报

  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
      clearTimeout(APP_STAY_DATA.timeControl);
      reportPageViewTimeOnVisbile();
    } else {
      reportAppStayTimeControl();
      PAGE_STAY_TIME.enterTimeTmp = Date.now();
      APP_STAY_DATA.enterTimeTmp = Date.now();
    }
  });

  if (deviceUtil.isIos) {
    document.addEventListener('pagehide', () => {
      clearTimeout(APP_STAY_DATA.timeControl);
      reportPageViewTimeOnVisbile();
    })
  }


  APP_STAY_DATA.enterTimeTmp = Date.now();
  reportAppStayTimeControl();

}

/**
 * 每隔5分钟上报一次用户在系统停留的总时长
 */
function reportAppStayTimeControl() {
  clearTimeout(APP_STAY_DATA.timeControl);
  APP_STAY_DATA.timeControl = setTimeout(() => {
    // 上报用户在系统停留的总时长
    APP_STAY_DATA.leaveTimeTmp = Date.now();
    APP_STAY_DATA.enterTimeTmp = APP_STAY_DATA.enterTimeTmp || Date.now();
    const appStayTime = APP_STAY_DATA.leaveTimeTmp - APP_STAY_DATA.enterTimeTmp;
    const appEvt = {
      'st': Math.floor(APP_STAY_DATA.enterTimeTmp / 1000),
      'et': Math.floor(APP_STAY_DATA.leaveTimeTmp / 1000),
      'dur': Math.floor(appStayTime / 1000)
    }
    reportTraceLog(SCENE_ENUM.SCENE_PAGE_STAYTIME_ALL, PAGE_ENUM.PAGE_HOME, appEvt);
    APP_STAY_DATA.enterTimeTmp = Date.now();
    return reportAppStayTimeControl();
  }, 5 * 60 * 1000);
}
